package com.atguigu.spzx.manager.service.product.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.spzx.manager.listener.CategoryReadListener;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.service.product.CategoryService;
import com.atguigu.spzx.model.entity.product.Category;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mahone
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> findByParentId(Long parentId) {
        // 查找所有根节点数据
       List<Category> categoryList = categoryMapper.findByParentId(parentId);
       // 对拿到的根节点数据集合遍历
        for (Category category : categoryList) {
            // 主键id
            Long id = category.getId();
            // 节点主键去表中查询是否有parentId=id
            Integer count = categoryMapper.countChildren(id);
            if (count > 0){
                // 说明有子节点
                category.setHasChildren(true);
            }
        }
        return categoryList;
    }

    @Override
    public void importData(MultipartFile multipartFile) {
        try {
            EasyExcel.read(multipartFile.getInputStream(),Category.class,new CategoryReadListener(categoryMapper)).
                    sheet("分类数据").doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void exportData(HttpServletResponse response) {
        List<Category> categories = categoryMapper.selectAll();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分类数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

            ServletOutputStream outputStream = response.getOutputStream();
            EasyExcel.write(outputStream,Category.class).sheet("分类数据").doWrite(categories);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
